﻿using Youz.Common.BLL;
using Youz.Common.Helper;
using Youz.Common.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;

namespace Youz.CreditRepay.Manage.Handlers
{
    /// <summary>
    /// LoginOrLogout 的摘要说明
    /// </summary>
    public class LoginOrLogout : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string type = context.Request.QueryString["type"];
            switch (type)
            {
                case "Login":
                    string result = Login(context);
                    context.Response.Write(result);
                    context.Response.End();
                    break;
                case "Logout":
                    Logout(context);
                    break;
                case "SwitchLanguage":
                    SwitchLanguage(context);
                    break;
                case "export":
                    Export(context);
                    break;
            }

        }

        private void Export(HttpContext context)
        {
            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.Charset = "utf-8";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.AppendHeader("content-disposition", "attachment;filename=\"" + HttpUtility.HtmlEncode(context.Request["txtName"] ?? DateTime.Now.ToString("yyyyMMdd")) + ".xls\"");
            context.Response.ContentType = "Application/ms-excel";
            context.Response.Write("<html>\n<head>\n");
            context.Response.Write("<style type=\"text/css\">\n.pb{font-size:13px;border-collapse:collapse;} " +
                           "\n.pb th{font-weight:bold;text-align:center;border:0.5pt solid windowtext;padding:2px;} " +
                           "\n.pb td{border:0.5pt solid windowtext;padding:2px;mso-number-format:0;}\n</style>\n</head>\n");

            var content = context.Request["txtContent"];
            content = Regex.Replace(content, @"\[([^\]]*)\]", "<$1>", RegexOptions.IgnoreCase | RegexOptions.Singleline);

            context.Response.Write("<body>\n" + content + "\n</body>\n</html>");
            context.Response.Flush();
            context.Response.End();
        }

        /// <summary>
        /// 切换系统语言
        /// </summary>
        /// <param name="context"></param>
        private void SwitchLanguage(HttpContext context)
        {
            string Language = context.Request.Form["LanguageKey"];
            Utility.CurrentLanguage = Language;
        }

        /// <summary>
        /// 登录系统
        /// </summary>
        public string Login(HttpContext context)
        {
            string UserName = context.Request.Form["UserName"];
            string Password = context.Request.Form["Password"];
            string ValidateCode = context.Request.Form["ValidateCode"];

            if (string.IsNullOrEmpty(UserName)) return Utility.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Other, "UserEmpty"));
            if (string.IsNullOrEmpty(Password)) return Utility.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Other, "PasswordEmpty"));
            if (string.IsNullOrEmpty(ValidateCode)) return Utility.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Login, "CheckCodeEmpty", "发生错误，验证码不能为空。"));

            string serverValidateCode = context.Session["ValidateCode"] as string ?? string.Empty;
            if (ValidateCode.ToLower() != serverValidateCode.ToLower()) return Utility.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Login, "CheckCodeError", "发生错误，验证码错误。"));

            Sys_AdminInfo model = new Sys_AdminInfoBLL().Get(UserName);
            if (model == null || model.LoginPwd != CommonHelper.GetSHA512(Password))
            {
                Utility.WriteLoginLog(false, UserName, (int)Utility.CurrentSiteType, "登錄失敗,用戶名或密碼錯誤!");
                return Utility.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Other, "UserOrPwdError", "登錄失敗,用戶名或密碼錯誤!"));
            }
            if (model.Status == 0)
            {
                Utility.WriteLoginLog(false, UserName, (int)Utility.CurrentSiteType, "登錄失敗,您的賬號被禁用!");
                return Utility.AjaxResult(false, Lang_LanguageBLL.LanguageByManage(LanguageModule.M_Other, "AccountDisabled", "登錄失敗,您的賬號被禁用!"));
            }

            string _LoginID = Utility.WriteLoginLog(true, UserName, (int)Utility.CurrentSiteType, "登錄成功");
            string userData = _LoginID + "," + model.FirstName + " " + model.LastName;

            //删除角色ID Cookie值
            CookieHelper.ClearCookie("CurrentRoleID");

            //创建票据
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.MemberAccount, DateTime.Now, DateTime.Now.AddMinutes(30), false, userData);
            //加密票据
            string authTicket = FormsAuthentication.Encrypt(ticket);
            //存储为cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket);
            cookie.Expires = ticket.Expiration;
            context.Response.Cookies.Add(cookie);
            
            return Utility.AjaxResult(true, "登錄成功！");
        }


        /// <summary>
        /// 退出系统
        /// </summary>
        /// <param name="context"></param>
        public void Logout(HttpContext context)
        {
            FormsAuthentication.SignOut();
            context.Response.Redirect("~/Login.aspx");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}